# -*- coding:utf-8 -*-
from testlib.file_path import TEMP_DIR
from datetime import datetime
import requests
import json
import logging
from os import path
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

logging.getLogger().level = logging.INFO


def get_new_access_token(ip: str):
    """ 获取新token """
    url = "https://{}/api/oauth2/v1/oauth/token".format(ip)

    data = '''{
    "xxxxx":"xxxxxxx",
    "xxxx":"xxxx"
    }'''

    headers = {"Content-Type": "application/json"}

    response = requests.request("POST", url, data=data, headers=headers, verify=False)
    if response.status_code != 200:
        raise Exception("{}获取token失败, HTTP状态码为：{}".format(url, response.status_code))

    response_dict = json.loads(response.text)
    response.close()

    return response_dict['accessToken']


def get_access_token(ip: str):
    """
        获取token。
        系统允许登录最大用户数为 1200，accessToken有效期为 1800 秒。
        设计从 accessToken.json 中获取 accessToken 逻辑为：
        如果文件中 accessToken 创建时间与当前的时间差小于 900秒，且使用次数小于 100 次，
        则使用文件中的 accessToken;
        否则向系统发送请求获取一个新的 accessToken，使用新的 accessToken，并将新的 accessToken写入文件
    :param ip: ip
    :return: accessToken
    """
    access_token_file_name = "accessToken_{}.json".format(ip.replace(".", "_"))
    access_toke_file_path = path.join(TEMP_DIR, access_token_file_name)

    # 获取当前时间
    now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # type: str
    now = datetime.strptime(now_str, '%Y-%m-%d %H:%M:%S')  # type: datetime

    # 如果该IP的 accessToken 文件不存在，直接写入新文件
    if not path.exists(access_toke_file_path):
        access_token_info = {
            "ip": ip,
            "create_time": now_str,
            "usage_count": 1,
            "accessToken": get_new_access_token(ip)
        }
        # 写入 accessToken 的信息
        with open(access_toke_file_path, "w") as f:
            json.dump(access_token_info, f)

        logging.info("使用的token信息为： {}".format(access_token_info))
        return access_token_info['accessToken']

    # 读取 accessToken 的信息
    with open(access_toke_file_path, "r") as f:
        current_info = json.load(f)  # type: dict
        logging.info("读取的token信息为：{}".format(current_info))

    # ip不匹配
    if current_info['ip'] != ip:
        current_info['ip'] = ip
        current_info['create_time'] = now_str
        current_info['usage_count'] = 0
        current_info['accessToken'] = get_new_access_token(ip)
    # 没有创建时间
    elif not current_info['create_time']:
        current_info['create_time'] = now_str
        current_info['usage_count'] = 0
        current_info['accessToken'] = get_new_access_token(ip)
    # 有创建时间
    else:
        # 文件中的时间
        time_record = datetime.strptime(current_info['create_time'], '%Y-%m-%d %H:%M:%S')  # type: datetime
        # 当前时间和文件中的时间差
        time_d = (now - time_record).total_seconds()
        logging.info("当前时间与文件中的 token 时间差为：{} s".format(time_d))

        # 如果时间差大于 900 秒， 更新token
        if time_d > 900:
            current_info['create_time'] = now_str
            current_info['usage_count'] = 0
            current_info['accessToken'] = get_new_access_token(ip)
        # 如果token使用次数大于 100 次，更新
        if current_info['usage_count'] > 99:
            current_info['create_time'] = now_str
            current_info['usage_count'] = 0
            current_info['accessToken'] = get_new_access_token(ip)

    # 写入 accessToken 的信息
    with open(access_toke_file_path, "w") as f:
        # current_info = json.dumps(current_info)
        current_info['usage_count'] += 1
        json.dump(current_info, f)

    logging.info("使用的token信息为： {}".format(current_info))
    return current_info['accessToken']


def get_headers(ip: str):
    headers = {
        'Content-Type': "application/json",
        'accept': "application/json, text/plain, */*",
        'accessToken': get_access_token(ip),
        'language-option': "zh-CN"
    }
    return headers


def get_headers_English(ip: str):
    headers = {
        'Content-Type': "application/json",
        'accept': "application/json",
        'accessToken': get_access_token(ip),
        'language-option': "en-US"
    }
    return headers


def get_export_header(ip: str):
    headers = {
        'Content-Type': "application/json",
        'accept': "application/octet-stream",
        'accessToken': get_access_token(ip),
        'language-option': "zh-CN"

    }
    return headers


def get_uopload_header(ip: str):
    headers = {
        'accessToken': get_access_token(ip),
        'language-option': "zh-CN"
    }
    return headers


def get_upload_header(ip: str):
    headers = {
        'accessToken': get_access_token(ip)
    }
    return headers


if __name__ == '__main__':
    print(get_access_token("127.0.0.1"))